<template>
	<el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" width="600" :destroy-on-close="true">
		<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="120px">
			<el-form-item prop="type" label="配置类型">
				<el-input v-model="dataForm.type" placeholder="配置类型" clearable maxlength="140"></el-input>
			</el-form-item>
            <el-form-item prop="key" label="配置key键">
				<el-input v-model="dataForm.key" placeholder="配置key键" clearable maxlength="140"></el-input>
			</el-form-item>
            <el-form-item prop="value" label="配置value值">
				<el-input v-model="dataForm.value" placeholder="配置value值" type="textarea" :rows="5" clearable maxlength="5000"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="submitHandle()">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus/es'
import { addSystemConfig, getSystemConfig } from '@/api/api'

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const dataFormRef = ref()
const dataForm = reactive({
	type: '',
	key: '',
	value: '',
})

const init = (key?: number) => {
	visible.value = true
	dataForm.type = ''
	dataForm.key = ''
	dataForm.value = ''
	// 重置表单数据
	if (dataFormRef.value) {
		dataFormRef.value.resetFields()
	}

	// id 存在则为修改
	if (key) {
        dataForm.key = key;
		getDetail(key)
	}
}
// 获取职务权限
const getDetail = (id) => {
	getSystemConfig(id).then(res => {
        delete res.data.created_at;
        delete res.data.updated_at;
        delete res.data.deleted_at;
		Object.assign(dataForm, res.data)
	})
}

const dataRules = ref({
	key: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	value: [{ required: true, message: '必填项不能为空', trigger: 'change' }]
})

// 表单提交
const submitHandle = () => {
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			return false
		}
        const params:any = {
            key: dataForm.key,
            value: dataForm.value,
        };
        if (dataForm.type) {
            params.type = dataForm.type;
        }
        if (dataForm.key) {
            params.key = dataForm.key;
        }
        addSystemConfig(params).then((result) => {
            if (result) {
                ElMessage.success({
                    message: '操作成功',
                    duration: 500,
                    onClose: () => {
                        visible.value = false
                        emit('refreshDataList')
                    }
                })
            }
        }).catch((err) => {
            
        });
	})
}

defineExpose({
	init
})
</script>
